package cn.tedu.st.security.controller;

import cn.tedu.st.base.exception.CustomerAuthenticationException;
import cn.tedu.st.security.pojo.dto.UserDTO;

import cn.tedu.st.base.result.JsonResult;
import cn.tedu.st.base.result.ResultCode;
import cn.tedu.st.security.pojo.vo.UserDetailsImpl;
import cn.tedu.st.security.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    //用户登录
    @PostMapping("/login")
    public JsonResult<Object> login(UserDTO userDTO) {
        log.debug("UserController用户登录信息={}", userDTO);
        Map<String, Object> map = userService.login(userDTO);
        if (!map.get("token").equals("") && !map.get("username").equals("")) {
            return JsonResult.custom(ResultCode.LOGIN_SUCCESS, map);
        }
        log.debug("UserController调用userService.login(userDTO)方法返回的jwt为={}", map);
        // 如果jwt没有长度，则返回失败
        return JsonResult.custom(ResultCode.LOGIN_FAILURE);
    }

    //退出登录
    @PostMapping("/logout")
    public JsonResult<Object> logout(HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("Authorization");
        if (ObjectUtils.isEmpty(token)) {
            token = request.getParameter("Authorization");
        }
        if (ObjectUtils.isEmpty(token)) {
            throw new CustomerAuthenticationException("token为空");
        }
        SecurityContext context = SecurityContextHolder.getContext();
        if (context.getAuthentication() != null) {
            // 清除认证信息
            context.setAuthentication(null);
            // 确保SecurityContextHolder完全清空
            SecurityContextHolder.clearContext();
            log.debug("清空上下文后={}", context.getAuthentication());
            redisTemplate.delete("token_" + token);
        }
        // 调用LogoutHandler（可选，根据实际需要）
        new SecurityContextLogoutHandler().logout(request, response, context.getAuthentication());
        return JsonResult.custom(ResultCode.LOGOUT_SUCCESS);
    }
}

